package net.lab1024.sa.admin.module.app.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import net.lab1024.sa.admin.module.app.req.MiniBindUserReq;
import net.lab1024.sa.admin.module.app.req.WxLoginFormReq;
import net.lab1024.sa.admin.module.app.rsp.LoginByPasswordRsp;
import net.lab1024.sa.admin.module.business.bjd.domain.entity.UserEntity;
import net.lab1024.sa.admin.module.business.bjd.dto.CustomerDto;
import net.lab1024.sa.admin.util.AppStpUtil;
import net.lab1024.sa.admin.util.RandomUtils;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.constant.RequestHeaderConst;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.enumeration.UserTypeEnum;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 *
 * @author guolong.zhang
 * @date 2025/02/09 09:17
 **/
@Service
@Slf4j
public class AppLoginService {

    @Autowired
    private WxMaService wxMaService;
    public ResponseDTO<LoginByPasswordRsp> bindUser(MiniBindUserReq req) {
        WxMaJscode2SessionResult session = miniOpenLogin(req.getCode());
        if (Objects.isNull(session)){
            return ResponseDTO.error(UserErrorCode.PARAM_ERROR,"小程序微信授权code错误");
        }
        String openId = session.getOpenid();
        // 解密用户信息
        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(),
                req.getEncryptedPhoneData(), req.getPhoneIV());

        log.info("getNewPhoneNoInfo:{}", wxMaPhoneNumberInfo.toString());
        String phone = wxMaPhoneNumberInfo.getPurePhoneNumber();

        UserEntity user = Db.lambdaQuery(UserEntity.class)
                .eq(UserEntity::getOpenId, openId)
                .one();
        LoginByPasswordRsp res = new LoginByPasswordRsp();
        if(user == null){
            user = registerMiniUser(openId);
            res.setIsFirstLogin(1);
        }
        AppStpUtil.login(user.getId());
        res.setUserId(user.getId());
        res.setNickName(user.getNickName());
        res.setUserName(user.getUserName());
        res.setToken(AppStpUtil.getTokenValue());
        return ResponseDTO.ok(res);
    }

    private UserEntity registerMiniUser(String openId) {
        UserEntity user = new UserEntity();
        user.setOpenId(openId);
        user.setUserName("WW"+RandomUtils.generateRandomUsername());
        user.setNickName("");
        user.setAvatar("");
        Db.save(user);
        return user;
    }


    public WxMaJscode2SessionResult miniOpenLogin(String code) {
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            if (Objects.isNull(session)){
                throw new BusinessException("小程序微信授权code错误");
            }
            log.info("小程序授权Session：{}", session);
            return session;
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("小程序微信授权code错误");
        }
    }

    public CustomerDto getLoginCustomer(String loginId, HttpServletRequest request) {
        UserEntity customer = Db.getById(loginId,UserEntity.class);
        if(null == customer){
            return null;
        }
        String ip = ServletUtil.getClientIP(request);
        String userAgent = ServletUtil.getHeaderIgnoreCase(request, RequestHeaderConst.USER_AGENT);
        CustomerDto dto = new CustomerDto();
        dto.setUserId(customer.getId());
        dto.setUserName(customer.getUserName());
        dto.setUserType(UserTypeEnum.APP_CUSTOMER);
        dto.setIp(ip);
        dto.setUserAgent(userAgent);
        return dto;
    }

    public ResponseDTO<LoginByPasswordRsp> wxLogin(WxLoginFormReq req) {
        WxMaJscode2SessionResult wxMaJscode2SessionResult = miniOpenLogin(req.getCode());
        if (Objects.isNull(wxMaJscode2SessionResult) || wxMaJscode2SessionResult.getOpenid() == null){
            return ResponseDTO.error(UserErrorCode.PARAM_ERROR,"小程序微信授权code错误");
        }
        String openid = wxMaJscode2SessionResult.getOpenid();
        UserEntity user = Db.lambdaQuery(UserEntity.class)
                .eq(UserEntity::getOpenId, openid)
                .one();
        LoginByPasswordRsp res = new LoginByPasswordRsp();
        if(user == null){
            user = registerMiniUser(openid);
            res.setIsFirstLogin(1);
        }
        AppStpUtil.login(user.getId());
        res.setUserId(user.getId());
        res.setNickName(user.getNickName());
        res.setUserName(user.getUserName());
        res.setToken(AppStpUtil.getTokenValue());
        return ResponseDTO.ok(res);
    }
}
